// src/pages/streaming/index.js
import getlogininfo from '../../../utils/getlogininfo';
import getIn from '../../../yali-sdk/utils/getIn';
import apiStartLivePlay from '../../../yali-sdk/business/live/api/apiStartLivePlay';
import { FAIL } from '../../../yali-sdk/utils/fail';
import { SUCCESS } from '../../../yali-sdk/utils/success';
import { addNotifier, notify, removeNotifier } from '../../../yali-sdk/utils/NotifyRegistryCenter';
import { LIVE_STATUS_END, LIVE_STATUS_START } from '../../../yali-sdk/business/live/api/constrants';
import apiCurrentLiveProduct from '../../../yali-sdk/business/live/api/apiCurrentLiveProduct';
import frequentClick from '../../../yali-sdk/utils/frequentClick';
import apiStopLivePlay from '../../../yali-sdk/business/live/api/apiStopLivePlay';
import apiEditProductPrice from '../../../yali-sdk/business/live/api/apiEditProductPrice';
import formattingDate from '../../../yali-sdk/utils/formattingDate';
import _list from '../../../yali-sdk/utils/list';
import apiLiveList from '../../../yali-sdk/business/live/api/apiAnchorLives';
import { getYaliUserInfo } from '../../../utils/checkAuth';
import { filterImg } from '../../imgBaseUrl';
import numberFormat from "../../numberFormat";

const COMMENT_MAX_NUMBER = 200;
Page({
    component: null,
    data: {
        showComment: false,
        userName: '',
        roomName: '',
        pureAudio: false,
        role: 'presenter', // 主播
        comment: [],
        inputMsg: [],
        openWind:false
    },

    onLoad(options) {
        options = options || {};
        let item;
        item = JSON.parse(options.item);
        if (typeof item === 'object') {
            this.setData({ item });
        }
        if (options.id) {
            this.liveList = new _list((params, cb) => global.actionDispatcher.execute(apiLiveList, params, cb), (core) => {
                const isLoaded = core.getIsLoaded();
                const isLoading = core.getIsLoading();
                const hasNext = core.getHasNext();
                const list = core.getScrollList();
                if (isLoaded) {
                    wx.hideLoading();
                    item = list && list.get(0);
                    if (item) {
                        item = item.toJS();
                    }
                    this.init(item);
                }
                this.setData({ isLoaded, isLoading, hasNext });
            }, { filter: list => list && list.map(it => it
                    .set('_end_time', formattingDate('yy/MM/dd hh:mm', new Date(it.get('end_time') * 1000)))
                    .set('_start_time', formattingDate('yy/MM/dd hh: mm', new Date(it.get('start_time') * 1000)))
                    .update('anchor', v => filterImg(v, 'head_photo'))
                    .update('shop_logo', v => filterImg({ v }, 'v').v)
                    .update('total_follow', v => v && numberFormat(v))
                    .update('total_live', v => v && numberFormat(v))
                    .update('total_live_zan', v => v && numberFormat(v))
                    .updateIn(['products', 'list'], list => list && list.map(it => filterImg(it, 'pic')).sortBy((val, index, obj) => val.get('order_id'), (a, b) => a - b))) });
            getYaliUserInfo().then((user) => {
                wx.showLoading({ mask: true });
                this.liveList.loadNew({
                    anchorId: user.id,
                    id: options.id,
                    isAnchor: true,
                    isProduct: true,
                    productRows: 50,
                });
            });
        }
        // 保持手机常亮
        wx.setKeepScreenOn({
          keepScreenOn: true,
        })
        addNotifier('UPDATE_LIVES_STATUS', this.refreshStatus, this);
        addNotifier('UPDATE_LIVES_CURRENT_PRODUCT', this.refreshCurrentProduct, this);
        addNotifier('UPDATE_PRODUCT_PRICE', this.refreshProductPrice, this);// 修改价格
        addNotifier('USER_ADD_PRODUCT_CART', this.refreshAddCart, this);
        addNotifier('SOCKET_CLOSE', this.socketClose, this);
        addNotifier('UPDATE_LIVES_ZAN', this.refreshZan, this);
        addNotifier('ADD_TO_CART', this.addCart, this);
        addNotifier('ADD_ORDER', this.addOrder, this);
        addNotifier('ANCHOR_FOLLOW', this.anchorFollow, this);
    },
    onUnload() {
      // 关闭保持手机常亮
      wx.setKeepScreenOn({
        keepScreenOn: false,
      })
    },
    init(item) {
        const self = this;
        const liveId = Number(getIn(item, ['id']));
        const roomName = getIn(item, ['title']);
        const userName = getIn(item, ['anchor', 'name']);

        wx.setNavigationBarTitle({
            title: roomName,
        });
        const endDuration = item.end_time * 1000 - Date.parse(new Date());// 结束倒计时
        if (endDuration <= 0) {
            setTimeout(() => {
                wx.navigateBack();
                wx.showModal({
                    content: '活动时间到，将结束直播!',
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            wx.showLoading({ mask: true });
                            global.actionDispatcher.execute(apiStopLivePlay, { liveId }, (f, fs) => {
                                if (f === SUCCESS) {
                                    wx.hideLoading();
                                    notify('UPDATE_LIVES_STATUS', { liveId, status: LIVE_STATUS_END });
                                } else if (f === FAIL) {
                                    wx.hideLoading();
                                }
                            });
                        }
                    },
                });
            }, endDuration);
        }
        getlogininfo({
            type: 'live_room',
            userName: this.data.userName,
            success() {
                self.pushComment({
                    type: 'sys',
                    content: '创建房间',
                });
                self.setData({
                    roomName,
                    userName,
                    liveId,
                    item,
                }, () => {
                    self.start();
                });
            },
            fail() {
                self.pushComment({
                    type: 'sys',
                    content: '创建房间失败',
                });
            },
        });
    },

    onShow() {
        const self = this;
		self.component && self.component.resume();
		if(self.component && self.component.data.exit == 5000){
			self.socketClose();
		}
    },
    onHide() {
        const self = this;
        self.component && self.component.pause();
    },
    onUnload() {
        const self = this;
        self.component && self.component.stop();
        getlogininfo({
            type: 'logout',
        });
        removeNotifier('UPDATE_LIVES_STATUS', this.refreshStatus, this);
        removeNotifier('UPDATE_LIVES_CURRENT_PRODUCT', this.refreshCurrentProduct, this);
        removeNotifier('UPDATE_PRODUCT_PRICE', this.refreshProductPrice, this);
        removeNotifier('SOCKET_CLOSE', this.socketClose, this);
        removeNotifier('UPDATE_LIVES_ZAN', this.refreshZan, this);
        removeNotifier('ADD_TO_CART', this.addCart, this);
        removeNotifier('ADD_ORDER', this.addOrder, this);
        removeNotifier('ANCHOR_FOLLOW', this.anchorFollow, this);
    },
    socketClose() {
        wx.showModal({
            content: '连接已断开，请退出房间，重新进入',
            showCancel: false,
            success(res) {
                wx.navigateBack();
            },
        });
    },
    // 更新活动状态
    refreshStatus(params) {
        if (params && params.liveId === getIn(this.data.item, ['id']) && params.status !== undefined) {
            this.setData({ item: { ...this.data.item, status: params.status, current_room: params.roomId } });
        }
    },
    refreshZan(params) {
        if (params && params.liveId === getIn(this.data.item, ['id']) && params.total !== undefined) {
            this.setData({ item: { ...this.data.item, total_live_zan: numberFormat(params.total) } });
        }
    },
    // 更新活动当前推荐产品
    refreshCurrentProduct(params) {
        if (params && params.liveId === getIn(this.data.item, ['id']) && params.productId !== undefined) {
            this.setData({ item: { ...this.data.item, current_product: params.productId } });
        }
    },
    // 用户添加产品到购物车，显示在评论里面
    addCart(params, self) {
        if (params.liveId === self.data.item.id && params.username) {
            self.pushComment({
                type: 'addCart',
                name: params.username,
            });
        }
    },
    addOrder(params, self) {
        if (params.liveId === self.data.item.id && params.username) {
            self.pushComment({
                type: 'addOrder',
                name: params.username,
            });
        }
    },
    anchorFollow(params, self) {
        if (params.liveId === self.data.item.id && params.username) {
            self.pushComment({
                type: 'anchorFollow',
                name: params.username,
            });
        }
    },
    // 更新产品价格
    refreshProductPrice(params) {
        const list = getIn(this.data.item, ['products', 'list']);
        if (params && params.unitPrice !== undefined && params.productId !== undefined && list) {
            this.data.item.products.list = list.map(it => ((it.id === params.productId) ? { ...it, unit_price: params.unitPrice } : it));
            this.setData({ item: this.data.item });
        }
    },
    onRoomEvent(e) {
        const self = this;
        const args = e.detail;
        switch (args.tag) {
            case 'created': {
                // 创建房间成功，通知后台
                const liveId = this.data.liveId;
                const roomId = args.roomID;
                const pushUrlId = args.pushUrlId;
                global.actionDispatcher.execute(apiStartLivePlay, { liveId, roomId, pushUrlId }, (f, fs) => {
                    if (f === SUCCESS) {
                        self.pushComment({
                            type: 'sys',
                            content: '创建房间成功',
                        });
                        notify('UPDATE_LIVES_STATUS', { liveId, status: LIVE_STATUS_START, roomId });

                        const current_product = getIn(self.data.item, ['current_product']);
                        const first_product = getIn(self.data.item, ['products', 'list', 0, 'id']);
                        if (!current_product && first_product) {
                            wx.showModal({
                                content: '是否立即推荐第一件产品？',
                                success(res) {
                                    if (res.confirm) {
                                        self._onCurrentProduct(first_product);
                                        // 保持手机常亮
                                        wx.setKeepScreenOn({
                                        keepScreenOn: true,
                                        })
                                    }
                                },
                            });
                        }
                    } else if (f === FAIL) {
                        wx.showToast({ title: '修改状态失败' });
                    }
                });

                break;
            }
            case 'roomClosed': {
                /* wx.showModal({
                    content: '房间已解散',
                    showCancel: false,
                    complete: () => {
                        wx.navigateBack({ delta: 1 });
                    },
                });*/
                break;
            }
            case 'error': {
                // wx.showToast({
                //     title: `${args.detail}[${args.code}]`,
                //     icon: 'none',
                //     duration: 1500,
                // });
				console.log('errorDetail:',args.detail);
				console.log('errorCode:', args.code);
                break;
            }
            case 'recvTextMsg': {
                // console.log('收到消息:', e.detail.detail);
                const msg = e.detail.detail;
                if (msg.userID) {
                    self.pushComment({
                        type: 'msg',
                        content: msg.message,
                        name: msg.userName,
                        time: msg.time,
                        isFollow: Number(msg.isFollow),
                    });
                }
                break;
            }
            default: {
                console.log('onRoomEvent default: ', e);
                break;
            }
        }
    },

    pushComment(msg) {
        if (this.data.comment.length >= COMMENT_MAX_NUMBER) {
            this.data.comment.splice(0, 1);
        }
        this.data.comment.push(msg);
        this.setData({
            comment: this.data.comment,
            toview: 'scroll-bottom', // 滚动条置底
        });
    },
    start() {
        const self = this;
        self.component = self.selectComponent('#id_liveroom');
        self.component.start();
    },
    onShareAppMessage() {
        let path = '/page/index/index?';
        this.options && Object.keys(this.options).map((key) => {
            path = `${path}&${key}=${this.options[key]}`;
        });
        return {
            title: '鸭梨直播',
            desc: '要讲点什么呢!',
            path,
        };
    },
    // 推荐产品
    onCurrentProduct(e) {
        frequentClick().then(() => {
            wx.showLoading({ mask: true });
            const product = getIn(e, ['currentTarget', 'dataset', 'product']);
            const productId = getIn(product, ['id']);
            const isCurret =getIn(e, ['currentTarget', 'dataset', 'isCurret']); //判断是否当前
            const isChangePrice = getIn(e, ['currentTarget', 'dataset', 'isChangePrice']); //判断允许改价
            const priceRange = getIn(e, ['currentTarget', 'dataset', 'priceRange']); //改价上下限
           // this._onCurrentProduct(productId)
            isCurret !== false && isChangePrice > 0 ? this._onCurrentProductPrice(productId, priceRange, product):this._onCurrentProduct(productId);

        });
    },
    _onCurrentProduct(productId) {
        const liveId = Number(this.data.liveId);
        liveId && global.actionDispatcher.execute(
            apiCurrentLiveProduct,
            { liveId, productId },
            (f) => {
                if (f === SUCCESS) {
                    this.setData({ openWind: false });
                    wx.hideLoading();
                    wx.showToast({ title: '操作成功' });
                    notify('UPDATE_LIVES_CURRENT_PRODUCT', { liveId, productId });
                } else if (f === FAIL) {
                    wx.hideLoading();
                }
            });
    },
    _onCurrentProductPrice(productId, priceRange, product){
     const currentPrice = getIn(product, ['unit_price']); //当前推荐产品价格
     let float_left_price,float_right_price;
     wx.hideLoading();
     if(priceRange!==0){ 
        let pr =Number(currentPrice)*priceRange/100;
        let prs = Math.round(pr*100)/100;

        float_left_price = Math.round((Number(currentPrice)-Number(prs))*100)/100;
        float_right_price = Math.round((Number(currentPrice) + Number(prs))*100)/100;
     }

     this.setData({
       openWind: true,
       changeProduct: { ...product, priceRange, float_left_price, float_right_price },
      //  productId:productId,
      //  priceRange:priceRange,
      //  currentPrice:currentPrice,
      //  float_left_price:float_left_price,
      //  float_right_price:float_right_price
     });
  },
  closeWin(){
        wx.hideLoading();
          this.setData({
            openWind: false
      });
    },
    updata_price(e){
     const updata_price = getIn(e, ['detail', 'value']);
     this.setData({
           updata_price: updata_price
        });
    },
    savePrice(e){
        const productId = getIn(e, ['currentTarget', 'dataset', 'productId']);
        const priceRange = getIn(e, ['currentTarget', 'dataset', 'priceRange']); //改价上下限 
        const unitPrices =getIn(this, [ 'data', 'updata_price']);
        const floatRightPrice =getIn(e, [ 'currentTarget', 'dataset','floatRightPrice']);
        const floatLeftPrice =getIn(e, [ 'currentTarget','dataset', 'floatLeftPrice']);
        const liveId =getIn(this, [ 'data','item', 'id']);//直播ID
        const unitPrice = Math.floor((Number(unitPrices))*100)/100;
        if(!unitPrice||unitPrice=='undefined'){
             wx.hideLoading();
               wx.showToast({
                    title: `请填写修改价格`,
                    icon: 'none',
                    duration: 1500,
                });
                return;
        }
        if(Number(unitPrice)<=0){
            wx.hideLoading();
            wx.showToast({
                    title: `价格必须大于0`,
                    icon: 'none',
                    duration: 1500,
                });
             return;
        }
        if(Number(unitPrice)<Number(floatLeftPrice) || Number(unitPrice)>Number(floatRightPrice)){
            wx.hideLoading();
            wx.showToast({
                    title: `设置价格有错误`,
                    icon: 'none',
                    duration: 1500,
                });
           return ;
        }
       
           global.actionDispatcher.execute(apiEditProductPrice, {liveId,productId,unitPrice}, (f, fs) => {
           if (f === SUCCESS) {
            wx.hideLoading();
            wx.showToast({
                    title: `设置价格成功`,
                    icon: 'none',
                    duration: 1500,
                });
           this.setData({
            openWind: false
             });   
           }
           else if (f === FAIL) {
            wx.hideLoading();
            wx.showToast({
                    title: `改价有误`,
                    icon: 'none',
                    duration: 1500,
                });

           }
        })
    }
});
